package com.classroom.smart.utils;

import com.classroom.smart.common.CommonResult;
import com.google.gson.Gson;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Map;

public class JSONUtils {
    //处理请求：将json数据，转成Java对象
    public static Map<String,String> transferObj(HttpServletRequest request){
        StringBuilder sb = new StringBuilder();
        //从请求中读取请求参数
        try (BufferedReader br =
                     new BufferedReader(new InputStreamReader(request.getInputStream() , "UTF-8"));){
            String line = null;
            while ((line=br.readLine())!=null){
                sb.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        Gson gson = new Gson();
        //将json数据，转成Map对象
        Map<String,String> map = gson.fromJson(sb.toString(), Map.class);
        return map;
    }

    //处理响应：将Java对象，转成json格式数据
    public static void writeJson(HttpServletResponse response , CommonResult commonResult){
        Gson gson = new Gson();
        //将Java对象，转成json格式数据
        String jsonStr = gson.toJson(commonResult);
        try (PrintWriter out = response.getWriter();){
            //将json数据，响应至客户端
            out.println(jsonStr);
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
